package main

import (
	"bufio"
	"fmt"
	"io"
	"log"
	"math"
	"os"
	"strings"
	"sync"
	"time"
)

var linePool = sync.Pool{
	New: func() interface{} {
		lines := make([]byte, 4*1024)
		return lines
	},
}

var stringPool = sync.Pool{
	New: func() interface{} {
		lines := ""
		return lines
	},
}

func Process(f *os.File) error {
	r := bufio.NewReader(f)

	var wg sync.WaitGroup
	for {
		buf := linePool.Get().([]byte)
		n, err := r.Read(buf)
		if err != nil || n == 0 {
			break
		}

		buf = buf[:n]
		nextUntilNewline, err := r.ReadBytes('\n')
		if err != io.EOF {
			buf = append(buf, nextUntilNewline...)
		}

		wg.Add(1)
		go func() {
			ProcessChunk(buf)
			wg.Done()
		}()
	}

	wg.Wait()
	return nil
}

func ProcessChunk(chunk []byte) {
	var wg2 sync.WaitGroup

	logs := stringPool.Get().(string)
	logs = string(chunk)
	linePool.Put(chunk)

	logsSlice := strings.Split(logs, "\n")
	stringPool.Put(logs)

	chunkSize := 300
	lines := len(logsSlice)
	// #goroutines
	numberOfThreads := lines / chunkSize
	if lines%chunkSize != 0 {
		numberOfThreads++
	}

	for i := 0; i < numberOfThreads; i++ {
		wg2.Add(1)

		startLine := i * chunkSize
		endLine := int(math.Min(float64((i+1)*chunkSize), float64(len(logsSlice))))
		go func(startLine, endLine int) {
			defer wg2.Done()

			for i := startLine; i < endLine; i++ {
				text := logsSlice[i]
				if len(text) == 0 {
					continue
				}
				fmt.Println(text)
			}

		}(startLine, endLine)
	}

	wg2.Wait()
	logsSlice = nil
}

func test1() {
	s := time.Now()
	filename := "../test.txt"
	file, err := os.Open(filename)
	if err != nil {
		fmt.Println("cannot able to read the file", err)
		return
	}

	defer file.Close()

	Process(file)
	fmt.Println("\n\nTime taken -", time.Since(s))
}

func test2() {
	s := time.Now()
	body, err := os.ReadFile("../test.txt")
	if err != nil {
		log.Fatalf("unable to read file: %v", err)
	}
	fmt.Println(string(body))
	fmt.Println("\n\nTime taken -", time.Since(s))
}

func test3() {
	s := time.Now()
	f, err := os.Open("../test.txt")
	if err != nil {
		log.Fatalf("unable to read file: %v", err)
	}
	defer f.Close()

	buf := make([]byte, 1024)
	for {
		n, err := f.Read(buf)
		if err == io.EOF {
			break
		}

		if err != nil {
			fmt.Println(err)
			continue
		}

		if n > 0 {
			fmt.Println(string(buf[:n]))
		}
	}
	fmt.Println("\n\nTime taken -", time.Since(s))
}

func main() {
	test1()
}
